<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\WeChatUser;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * {@inheritdoc}
     */
    public function username()
    {
        return 'username';
    }

    /**
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function redirectToProvider()
    {
        return Socialite::driver('wechat')->redirect();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     * @throws \Illuminate\Validation\ValidationException
     */
    public function handleProviderCallback(Request $request)
    {
        $state = $request->get('state') ?? '1';

        $request->session()->put('state', $state);

        $user = Socialite::driver('wechat')->user();

        $userInfo = $user->user;

        /** @var WeChatUser $weChatUser */
        $weChatUser = WeChatUser::query()->firstOrNew([
            'openid' => $user->getId()
        ], [
            'nickname' => $user->getNickname(),
            'sex' => $userInfo['sex'] ?? 0,
            'language' => $userInfo['language'] ?? '',
            'city' => $userInfo['city'] ?? '',
            'province' => $userInfo['province'] ?? '',
            'country' => $userInfo['country'] ?? '',
            'avatar' => $user->getAvatar(),
        ]);

        if ($weChatUser->user_id) {
            // 登录已绑定用户
            $userModel = User::query()->find($weChatUser->user_id);

            if ($userModel) {
                Auth::login($userModel);

                return $this->sendLoginResponse($request);
            } else {
                return $this->sendFailedLoginResponse($request);
            }
        } else {
            // 创建新用户
            $username = $user->getNickname() . Str::random(6);

            /** @var User $userModel */
            $userModel = User::query()->create([
                'name' => $user->getNickname() ?? $username,
                'username' => $username,
                'email' => $username . '@example.org',
                'password' => '',
            ]);

            // 绑定新用户
            $weChatUser->user_id = $userModel->id;

            $weChatUser->save();

            // 登录新用户
            Auth::login($userModel);

            return $this->sendLoginResponse($request);
        }
    }
}
